package org.example.notificationservice.sender;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.example.notificationservice.config.SmsProperties;
import org.example.notificationservice.entity.Notification;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class SmsNotificationSender implements NotificationSender {
    private final IAcsClient client;
    private final SmsProperties smsProperties;

    public SmsNotificationSender(SmsProperties smsProperties) {
        this.smsProperties = smsProperties;
        DefaultProfile profile = DefaultProfile.getProfile(
            smsProperties.getRegionId(),
            smsProperties.getAccessKeyId(),
            smsProperties.getAccessKeySecret()
        );
        this.client = new DefaultAcsClient(profile);
    }

    @Override
    public void send(Notification notification) {
        try {
            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(notification.getMetadata().get("phone").toString());
            request.setSignName(smsProperties.getSignName());
            request.setTemplateCode(notification.getMetadata().get("templateCode").toString());
            request.setTemplateParam(notification.getMetadata().get("templateParam").toString());

            client.getAcsResponse(request);
            log.info("SMS sent successfully to: {}", request.getPhoneNumbers());
        } catch (Exception e) {
            log.error("Failed to send SMS notification", e);
            throw new RuntimeException("Failed to send SMS notification", e);
        }
    }

    @Override
    public boolean supports(Notification.NotificationType type) {
        return Notification.NotificationType.SMS.equals(type);
    }
}